<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="audio-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <div class="section-title">基本信息</div>
        
        <el-form-item label="主标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入音频主标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="副标题" prop="subtitle">
          <el-input
            v-model="formData.subtitle"
            placeholder="请输入音频副标题（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" class="w-full">
            <el-option label="英文" value="english" />
            <el-option label="中文" value="chinese" />
          </el-select>
        </el-form-item>

        <el-form-item label="语言类型" prop="language">
          <el-select v-model="formData.language" placeholder="请选择语言类型" clearable class="w-full">
            <el-option label="英文" value="en" />
            <el-option label="中文" value="zh" />
            <el-option label="双语" value="bilingual" />
          </el-select>
        </el-form-item>

        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number
            v-model="formData.sortOrder"
            :min="0"
            :max="9999"
            placeholder="排序权重，数字越大越靠前"
            class="w-full"
          />
        </el-form-item>

        <el-form-item label="状态" prop="enabled">
          <el-switch
            v-model="formData.enabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </div>

      <!-- 绘本绑定 -->
      <div class="form-section">
        <div class="section-title">绘本绑定</div>
        
        <el-form-item label="绑定绘本">
          <div class="book-binding">
            <div v-if="selectedBookInfo" class="selected-book-info">
              <div class="book-info-content">
                <Icon icon="ep:document" class="mr-2" />
                <span>{{ selectedBookInfo }}</span>
              </div>
              <el-button type="text" @click="clearBookBinding" class="clear-btn">
                <Icon icon="ep:close" />
              </el-button>
            </div>
            <el-button v-else type="primary" plain @click="openBookSelector">
              <Icon icon="ep:plus" class="mr-1" />
              选择绘本
            </el-button>
          </div>
          <div class="form-tip">
            <Icon icon="ep:info-filled" class="mr-1" />
            推荐绑定到具体的绘本，以便更精准地关联音频内容
          </div>
        </el-form-item>
      </div>

      <!-- 文件上传 -->
      <div class="form-section">
        <div class="section-title">文件上传</div>
        
        <el-form-item label="音频文件" prop="audioFile">
          <el-upload
            ref="audioUploadRef"
            :action="audioUploadUrl"
            :headers="uploadHeaders"
            :data="audioUploadData"
            :before-upload="beforeAudioUpload"
            :on-success="onAudioUploadSuccess"
            :on-error="onAudioUploadError"
            :file-list="audioFileList"
            :limit="1"
            accept=".mp3,.wav,.m4a,.aac"
            name="audio"
            drag
          >
            <Icon icon="ep:upload-filled" :size="40" class="text-gray-400" />
            <div class="upload-text">
              <div>将音频文件拖到此处，或<em>点击上传</em></div>
              <div class="upload-tip">支持 MP3、WAV、M4A、AAC 格式，文件大小不超过 50MB</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图片">
          <el-upload
            ref="coverUploadRef"
            :action="coverUploadUrl"
            :headers="uploadHeaders"
            :before-upload="beforeCoverUpload"
            :on-success="onCoverUploadSuccess"
            :on-error="onCoverUploadError"
            :file-list="coverFileList"
            :limit="1"
            accept=".jpg,.jpeg,.png,.gif"
            name="cover"
            list-type="picture-card"
          >
            <Icon icon="ep:plus" />
            <template #tip>
              <div class="upload-tip">支持 JPG、PNG、GIF 格式，文件大小不超过 5MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>

    <!-- 绘本选择器 -->
    <BookSelector ref="bookSelectorRef" @confirm="onBookSelected" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage as message } from 'element-plus'
import { getAccessToken } from '@/utils/auth'
import * as AudioApi from '@/api/reading/audio'
import type { AudioResourceUpdateReqVO } from '@/api/reading/audio'
import BookSelector from './components/BookSelector.vue'

interface FormData {
  id?: number
  title: string
  subtitle?: string
  audioUrl?: string
  cover?: string
  duration?: number
  category: string
  language?: string
  bookId?: number
  bookSetId?: number
  sortOrder?: number
  enabled: boolean
  tempId?: number // 新增时的临时ID，用于封面上传
}

const emit = defineEmits<{
  (e: 'success'): void
}>()

const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const submitLoading = ref(false)

const formRef = ref()
const audioUploadRef = ref()
const coverUploadRef = ref()
const bookSelectorRef = ref()

const formData = ref<FormData>({
  title: '',
  subtitle: '',
  category: 'english',
  language: 'en',
  sortOrder: 0,
  enabled: true,
  tempId: undefined // 新增时的临时ID
})

const selectedBookInfo = ref('')
const audioFileList = ref<Array<{ name: string; url: string }>>([])
const coverFileList = ref<Array<{ name: string; url: string }>>([])

// 上传配置
const uploadHeaders = {
  Authorization: 'Bearer ' + getAccessToken()
}

const audioUploadUrl = import.meta.env.VITE_BASE_URL + '/admin-api/reading/audio-file/resource'
const coverUploadUrl = computed(() => {
  // 如果有ID（编辑模式）或者有临时ID（新增模式），则返回上传URL
  const audioId = formData.value.id || formData.value.tempId
  const url = audioId
    ? `${import.meta.env.VITE_BASE_URL}/admin-api/reading/audio-file/audio/${audioId}/cover`
    : ''
  console.log('coverUploadUrl computed:', {
    id: formData.value.id,
    tempId: formData.value.tempId,
    audioId,
    url,
    baseUrl: import.meta.env.VITE_BASE_URL
  })
  return url
})

const audioUploadData = computed(() => ({
  category: formData.value.category,
  language: formData.value.language
}))

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入音频标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  subtitle: [
    { max: 200, message: '副标题长度不能超过 200 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 方法
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '创建音频' : '编辑音频'
  isEdit.value = type === 'update'

  resetForm()

  if (id) {
    loadAudioData(id)
  } else if (type === 'create') {
    // 新增模式时获取临时ID，用于封面上传
    try {
      console.log('开始获取临时ID...')
      const response = await AudioApi.getNextAudioResourceId()
      console.log('获取临时ID响应:', response)

      // 检查响应格式，兼容不同的返回格式
      let tempId
      if (typeof response === 'number') {
        // 直接返回数字
        tempId = response
      } else if (response && response.code === 0) {
        // 标准响应格式
        tempId = response.data
      } else if (response && typeof response.data === 'number') {
        // 其他格式
        tempId = response.data
      }

      if (tempId) {
        formData.value.tempId = tempId
        console.log('获取临时ID成功:', tempId)
        // 强制触发计算属性重新计算
        nextTick(() => {
          console.log('临时ID设置后，封面上传URL:', coverUploadUrl.value)
        })
      } else {
        console.error('获取临时ID失败，响应格式不正确:', response)
        message.error('获取临时ID失败，响应格式不正确')
      }
    } catch (error) {
      console.error('获取临时ID失败:', error)
      message.error('获取临时ID失败，封面上传功能可能受影响')
    }
  }
}

const resetForm = () => {
  formData.value = {
    title: '',
    subtitle: '',
    audioUrl: '',
    cover: '',
    duration: undefined,
    category: 'english',
    language: 'en',
    sortOrder: 0,
    enabled: true,
    tempId: undefined
  }
  selectedBookInfo.value = ''
  audioFileList.value = []
  coverFileList.value = []

  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const loadAudioData = async (id: number) => {
  try {
    const data = await AudioApi.getAudioResource(id)
    formData.value = { ...data }
    
    // 设置绘本信息
    if (data.bookTitle || data.bookSetTitle) {
      if (data.bookTitle) {
        selectedBookInfo.value = `绘本: ${data.bookTitle} (${data.bookSetTitle})`
      } else {
        selectedBookInfo.value = `绘本集: ${data.bookSetTitle}`
      }
    }
    
    // 设置文件列表
    if (data.audioUrl) {
      audioFileList.value = [{
        name: '音频文件',
        url: data.audioUrl
      }]
    }
    
    if (data.cover) {
      coverFileList.value = [{
        name: '封面图片',
        url: data.cover
      }]
    }
  } catch (error) {
    message.error('加载音频数据失败')
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    submitLoading.value = true

    if (isEdit.value && formData.value.id) {
      await AudioApi.updateAudioResource(formData.value as AudioResourceUpdateReqVO)
      message.success('更新成功')
    } else {
      await AudioApi.createAudioResource(formData.value)
      message.success('创建成功')
    }

    emit('success')
    handleClose()
  } catch (error: any) {
    console.error('提交失败:', error)
    if (error?.response?.data?.msg) {
      message.error('操作失败: ' + error.response.data.msg)
    } else if (error?.message) {
      message.error('操作失败: ' + error.message)
    } else {
      message.error('操作失败，请稍后重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 绘本选择相关
const openBookSelector = () => {
  bookSelectorRef.value.open()
}

const onBookSelected = (result: any) => {
  // 现在只支持绘本绑定
  if (result.type === 'book' && result.bookId) {
    formData.value.bookSetId = result.bookSetId
    formData.value.bookId = result.bookId
    selectedBookInfo.value = `${result.bookTitle} (来自: ${result.bookSetTitle})`
  }
}

const clearBookBinding = () => {
  formData.value.bookSetId = undefined
  formData.value.bookId = undefined
  selectedBookInfo.value = ''
}

// 文件上传相关
const beforeAudioUpload = (file: File) => {
  const isAudio = ['audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/aac'].includes(file.type)
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isAudio) {
    message.error('只能上传音频文件!')
    return false
  }
  if (!isLt50M) {
    message.error('音频文件大小不能超过 50MB!')
    return false
  }
  return true
}

const onAudioUploadSuccess = (response: any) => {
  if (response.code === 0) {
    const uploadResult = response.data
    message.success(`音频上传成功${uploadResult.duration ? `，时长: ${uploadResult.durationText}` : ''}`)

    // 保存音频信息到表单数据
    formData.value.audioUrl = uploadResult.audioUrl
    formData.value.duration = uploadResult.duration

    console.log('音频上传成功，URL:', uploadResult.audioUrl, '时长:', uploadResult.duration, '秒')
  } else {
    message.error('音频上传失败: ' + response.msg)
  }
}

const onAudioUploadError = () => {
  message.error('音频上传失败')
}

const beforeCoverUpload = (file: File) => {
  // 检查上传URL是否有效
  if (!coverUploadUrl.value) {
    message.error('上传地址无效，请先保存音频基本信息或等待临时ID获取完成')
    return false
  }

  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    message.error('图片文件大小不能超过 5MB!')
    return false
  }

  console.log('封面上传前检查通过，上传URL:', coverUploadUrl.value)
  return true
}

const onCoverUploadSuccess = (response: any) => {
  if (response.code === 0) {
    message.success('封面上传成功')
    // 后端返回完整URL，前端直接使用（后端会在存储时转换为相对路径）
    formData.value.cover = response.data
    console.log('封面上传成功，URL:', response.data)
  } else {
    message.error('封面上传失败: ' + response.msg)
  }
}

const onCoverUploadError = () => {
  message.error('封面上传失败')
}

defineExpose({
  open
})
</script>

<style scoped>
.audio-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.book-binding {
  width: 100%;
}

.selected-book-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 6px;
}

.book-info-content {
  display: flex;
  align-items: center;
  color: #1e40af;
  font-size: 14px;
}

.clear-btn {
  color: #6b7280;
  padding: 4px;
}

.upload-text {
  text-align: center;
  color: #606266;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.form-tip {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style>
